var express = require("express");
var router = express.Router();
const fs = require("fs");
const fsPromises = require("fs").promises;
const axios = require("axios");
const { APPURL } = require("./config");


// post转get
router.post("/api/agv/list", async function (req, res, next) {
  try {
    //发起实际的API请求
    const apiResponse = await axios.get(APPURL + "/api/agv/list", req.body);
    //返回API响应给前端
    res.json(apiResponse.data);
  } catch (error) {
    //处理错误
    console.error("POST Error fetching data from API:", error.message);
    res.status(500).json({ error: "Internal Server Error" });
  }
});
// 保存配置文件
router.post("/api/agv/setFileInfo", async (req, res) => {
  // console.log(req.body);
  try {
    // 删除old文件,
    try {
      let oldStr = `./dist/config.json`;
      await fsPromises.rm(oldStr); // 使用 await 等待删除完成
    } catch {

    }
    // 新增new文件
    let newStr = `./dist/config.json`;
    let content = `{
  "ip": "127.0.0.1",
  "factor": ${req.body.factor},
  "multiple": 60,
  "ctxTranslate": {
      "x": ${req.body.ctxTranslate.x},
      "y": ${req.body.ctxTranslate.y}
  }
}`;
    await fsPromises.writeFile(newStr, content); // 使用 await 等待写入完成
    res.send({ success: true, message: "保存成功" });
  } catch (error) {
    console.log(error);
    res
      .status(500)
      .send({ success: false, message: "提交失败", error: error.message });
  }
});
// 读取配置文件信息
router.get("/api/agv/getFileInfo", async (req, res) => {
  try {
    let str = `./dist/config.json`;
    let content = await fsPromises.readFile(str, "utf8");
    let obj = JSON.parse(content);
    res.send({ success: true, message: "读取成功", data: obj });
  } catch (error) {
    res.status(500).send(error)
  }
});
module.exports = router;
